import {Workbench} from './workbench.js';

window.app = new Workbench();

window.socketClient = new class socketClient {
    constructor(app) {
        this.app = app;
        this.socket = null;
        this.app.on('load', () => this.initialize());
        this.app.on('chatClose', () => this.dispose());
        this.app.on('send', (e) => this.doSend(e));
        this.messages = [];
        this.sessionReady = false;
        this.app.login();
    }
    doSend(e) {
        this.socket.emit('chat message', e.content);
    };
    doUpload() { };
    render(msg) {
        if (this.sessionReady) {
            while (this.messages.length > 0) {
                var m = this.messages.shift();
                this.app.onMessage(m);
            }
            this.app.onMessage(msg);
        }
        else {
            this.messages.push(msg);
        }
    }
    initialize() {
        this.socket = io('127.0.0.1:9000', {
            path: '/workbench'
          })
        this.socket.on('chat message', (d) => this.onMessage(d));
    }
    dispose() {
        this.socket && this.socket.disconnect();
    }
    onMessage(d) {
        var m = {};
        try {
            m = JSON.parse(d);
            console.log(m);
        } catch{

        }
        if (m.typeName == 'SESSION_READY') {//1
            //this.app.onSessionReady(m);
            this.sessionReady = true;
        }
        else {
            if (m.typeName == 'SYSTEM') {//0
                m.content = '系统消息：' + m.content;
                this.render(m);
            }
            else if (m.typeName == 'BUDDY_CHAT') {
                this.render(m.content);
            }
            else if (m.typeName == 'GROUP_CHAT') {//100
                m.content = m.from.nickName + '：' + m.content;
                this.render(m);
            }
            else if (m.typeName == "BUDDY_ENTER") {//4
                m.content_bk = m.content;
                m.content = '系统消息：' + m.from.nickName + ' 加入聊天, 当前' + m.content.numberOfOnlineUsers + '人在线';
                m.from = null;
                this.render(m);
            }
            else if (m.typeName == 'BUDDY_LEAVE') {
                m.content_bk = m.content;
                m.content = '系统消息：' + m.from.nickName + ' 离开聊天, 当前' + m.content.numberOfOnlineUsers + '人在线';
                m.from = null;
                this.render(m);
            }
            else if (m.typeName == 'AGENT_SCHED') {
                this.app.onAgentSched(m);
            }
            else {
                this.render(m);
                console.log('unknown msg type');
            }
        }
    }
}(window.app);